﻿package net.jejer.autoproxy2pac3;

import java.io.IOException;
import javax.servlet.http.*;

//URL Fetch
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
//import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;

//Data
import javax.jdo.JDODataStoreException;
import javax.jdo.PersistenceManager;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import net.jejer.autoproxy2pac3.PMF;
import net.jejer.autoproxy2pac3.PacData;

@SuppressWarnings("serial")
public class fetch extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");

		String line;
		StringBuffer sb = new StringBuffer();
		resp.setContentType("text/plain; charset=utf-8");

		try {
			URL url = new URL("http://autoproxy2pac.appspot.com/pac/ssh-d");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);// 使用 URL 连接进行输入
			connection.setRequestMethod("GET");
			// 取得网页源码
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				// 每次读取一行输出
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
				reader.close();
				
				int originalLength = connection.getHeaderFieldInt("Content-Length", 2147483647);
				if (sb.length() >= originalLength){
					// 长度正确,写入数据库
					PersistenceManager pm = PMF.get().getPersistenceManager();
					Key k = KeyFactory.createKey(PacData.class.getSimpleName(), "SSH");
					
					try {
						PacData oldData = pm.getObjectById(PacData.class, k);
						pm.deletePersistent(oldData);
					} catch (JDODataStoreException e) {
			            //
			        }
					
					PacData pacData = new PacData("SSH", connection.getHeaderField("Last-Modified"), sb.toString(), originalLength);
			        pacData.setKey(k);
			        try {
			            pm.makePersistent(pacData);
			        } finally {
			            pm.close();
			        }
			        
			        resp.getWriter().println("读取与保存成功");
				} else {
					// 长度错误
					resp.getWriter().println("长度错误");
				}
			} else {
				// Server returned HTTP error code.
				resp.getWriter().println("远端返回错误");
				resp.getWriter().println(connection.getResponseMessage());
			}
			connection.disconnect();
		} catch (MalformedURLException e) {

		} catch (IOException e) {

		}

		//resp.getWriter().println(sb.toString());
	
	}
}